package beegoRoute

import (
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"net/http"
	"regexp"
)

var RoutePathRegexp = regexp.MustCompile(`[\/\\]{2,}`)

type BeegoEngine struct {
	engine       *web.HttpServer
	groupServers map[string]*GroupServer // groupName Server
}

func NewDefaultEngine() *BeegoEngine {
	web.BConfig.RecoverPanic = true
	g := &BeegoEngine{
		engine:       web.NewHttpServerWithCfg(web.BConfig),
		groupServers: make(map[string]*GroupServer),
	}
	web.BeeApp = g.engine
	return g
}

func (e *BeegoEngine) NameSpace(nameSpace string, params ...web.LinkNamespace) *BeegoEngine {
	web.BeeApp = e.engine
	web.AddNamespace(web.NewNamespace(nameSpace, params...))
	return e
}
func (e *BeegoEngine) AddGroupServers(gs ...*GroupServer) *BeegoEngine {
	for _, g := range gs {
		e.groupServers[g.groupPath] = g
		e.pathHandle(g)
	}
	return e
}
func (e *BeegoEngine) pathHandle(ginGroup *GroupServer) {
	e.handleMethod(ginGroup.handle.method, ginGroup.groupPath, ginGroup.handle.handler)
	for routePath, route := range ginGroup.routeMap {
		routePath := RoutePathRegexp.ReplaceAllString(ginGroup.groupPath+"/"+routePath, "/")
		for method, handle := range route.handleFunMap {
			fmt.Println(method, routePath)
			e.handleMethod(method, routePath, handle)
		}

	}
}

func (e *BeegoEngine) handleMethod(method string, routePath string, handle web.HandleFunc) {
	switch method {
	//http.GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE
	case http.MethodGet:
		e.engine.Get(routePath, handle)
	case http.MethodHead:
		e.engine.Head(routePath, handle)
	case http.MethodPost:
		e.engine.Post(routePath, handle)
	case http.MethodPut:
		e.engine.Put(routePath, handle)
	case http.MethodPatch:
		e.engine.Patch(routePath, handle)

	case http.MethodDelete:
		e.engine.Delete(routePath, handle)

	case http.MethodOptions:
		e.engine.Options(routePath, handle)
	}
}

func (e *BeegoEngine) Run(addr string, mws ...web.MiddleWare) {
	e.engine.Run(addr, mws...)
}
func (e *BeegoEngine) Engine() *web.HttpServer {
	return e.engine
}

//}func (e *BeegoEngine) GlobalMiddleware(middleware ...webS.HandlerFunc) *BeegoEngine {
//	e.engine.Use(middleware...)
//	return e
//}
//func (e *BeegoEngine) SetStaticPath(webRelativePath, relativeDir string) *BeegoEngine {
//	e.engine.Static(webRelativePath, filepath.Dir(relativeDir))
//	return e
//}

//func (e *BeegoEngine) RunEngine(port string) {
//	e.engine.RedirectTrailingSlash = false
//	err := e.engine.Run(port)
//	if err != nil {
//		logUtils.LogPrintln(1, "webS Run Fail"+port)
//		return
//	}
//}
//
//func (e *BeegoEngine) ListenAndServe(port string) {
//	err := http.ListenAndServe(port, e.engine.Handler())
//	if err != nil {
//		return
//	}
//}
